package cn.net.yugu.doraemon.common.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * 手机号码工具类
 * 
 * @author liuyu
 */
public class MobileUtils {

    public static void putMobileMaskMap(Map map , String k, String v) {
        map.put(k, maskPhoneNumber(v));
        map.put(k + "_encryption", encryptMobile(v));
    }

    public static String maskPhoneNumber(String mobile) {
        if (StringUtils.isBlank(mobile)){
            return "";
        }
        if (mobile.length() >= 11) {
            String before = mobile.substring(0, 3);
            String after = mobile.substring(7);
            return before + "****" + after;
        } else {
            return mobile;
        }
    }

    /**
     * 加密
     * 加密规则 base64（base64(17899998888)+,+ 时间不是前8位+时间戳前8位）
     * 加密后将密文的前2位与后2位进行对调
     * 再返回密文
     * @param mobile
     * @return
     */
    public static String encryptMobile(String mobile){
        if (StringUtils.isEmpty(mobile)){
            return "";
        }
        long dateTime = new Date().getTime();
        String datetTimeStr = String.valueOf(dateTime);
        String time1 = datetTimeStr.substring(0,8);
        String time2 = datetTimeStr.substring(8);
        String encode = new String(Base64.encodeBase64(mobile.getBytes()));
        encode = encode + "," + time2 + time1;
        encode = new String(Base64.encodeBase64(encode.getBytes()));
        String encode1 = encode.substring(0,2);
        String encode2 = encode.substring(2, encode.length()- 2);
        String encode3 = encode.substring(encode.length() - 2);
        encode = encode3 + encode2 + encode1;
        return encode;
    }

}
